package test.my.com.myapplicationtest.dong_tai_yuan_quan_tongji;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.provider.SyncStateContract;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;

import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import test.my.com.myapplicationtest.R;
import test.my.com.myapplicationtest.utils.LogUtil;

/**
 * Author : Cooper
 * Time : 2017/9/14  14:10
 * Description : 动态圆圈统计View
 */
public class DynamicCircleStatisticsView extends View {

    private Context mContext;

    private int mWidth = 100;
    private int mHeight = 100;

    private int mArcColor; // 圆弧颜色
    private int mArcStrokeWidth; // 圆弧宽度
    private int mStartAngle; // 圆弧起始角度
    private int mAnimatorTime; // 圆弧动画时间
    private RectF mRectF;
    private int mSpace = 30; // 圆弧偏移（解决边缘显示不全）

    private int mSweepAngle; // 圆弧画的角度
    private ValueAnimator valueAnimator;

    private List<ArcEntity> mArcEntityList = new ArrayList<>();

    private int dynamicAngle;
    private int shiftingAngle = 70;

    public DynamicCircleStatisticsView(Context context) {
        super(context);
    }

    public DynamicCircleStatisticsView(Context context, @Nullable AttributeSet attrs) {
        this(context,attrs,0);
    }

    public DynamicCircleStatisticsView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.YuanHuArcView,defStyleAttr,0);
        mArcColor = ta.getColor(R.styleable.YuanHuArcView_arcColor, Color.RED);
        mArcStrokeWidth = ta.getDimensionPixelOffset(R.styleable.YuanHuArcView_arcStrokeWidth,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2,
                getResources().getDisplayMetrics()));
        mStartAngle = ta.getInt(R.styleable.YuanHuArcView_startAngle,0);
        mSweepAngle = ta.getInt(R.styleable.YuanHuArcView_sweepAngle,100);
        mAnimatorTime = ta.getInt(R.styleable.YuanHuArcView_animatorTime,1000);
        ta.recycle();

        init();
    }

    private void init() {
        valueAnimator = ValueAnimator.ofInt(0,mSweepAngle);
        valueAnimator.setDuration(mAnimatorTime);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                dynamicAngle = (int) animation.getAnimatedValue();
                for (int i=0;i<mArcEntityList.size();i++) {
                    ArcEntity arcEntity = mArcEntityList.get(i);
                    if (i == 0) {
                        if (dynamicAngle <= arcEntity.getEndAngle()) {
                            arcEntity.setSweepAngle(arcEntity.getEndAngle()); // 当动态圆弧到达每个圆弧画的结束的位置时，停止在这个角度绘画
                        } else {
                            arcEntity.setSweepAngle(dynamicAngle);
                        }
                    } else {
                        int d1 = dynamicAngle+shiftingAngle;
                        if (d1 <= 0) {
                            if (d1 <= arcEntity.getEndAngle()) {
                                arcEntity.setSweepAngle(arcEntity.getEndAngle()); // 当动态圆弧到达每个圆弧画的结束的位置时，停止在这个角度绘画
                            } else {
                                arcEntity.setSweepAngle(d1);
                            }
                        }
                    }
                }
                DynamicCircleStatisticsView.this.invalidate();
            }
        });
    }

    public void setBussinessData(List<DynamicCircleStatisticsView.DataEntity> dataList) {
        if (dataList == null || dataList.size() == 0) {
            return;
        }
        Collections.sort(dataList, new Comparator<DataEntity>() {
            @Override
            public int compare(DataEntity lhs, DataEntity rhs) {
                return (int)(lhs.data - rhs.data);
            }
        });

        float sum = 0f; // 业务数据总值
        for (DataEntity data : dataList) {
            sum+=data.data;
        }
        ArcEntity arcEntityBottom = new ArcEntity(mStartAngle, mSweepAngle, dataList.get(dataList.size()-1).color);
        mArcEntityList.add(arcEntityBottom);

        float angle = 0f;
        for (DataEntity data : dataList) { // 将业务数据转换为圆弧数据
            ArcEntity arcEntity = new ArcEntity(mStartAngle-shiftingAngle, mSweepAngle+shiftingAngle+angle, data.color);
            mArcEntityList.add(arcEntity);
            angle += data.data*360/sum;
        }

        LogUtil.e("");
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
        mRectF = new RectF(mSpace,mSpace,mWidth-mSpace,mHeight-mSpace);
    }

    private int measureWidth(int widthMeasureSpec){
        int result = 0;
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);
        if(specMode == MeasureSpec.EXACTLY){
            result = specSize;
        } else {
            result = mWidth;
            if(specMode == MeasureSpec.AT_MOST){
                result = Math.min(result, specSize);
            }
        }
        this.mWidth = result;
        return result;
    }

    private int measureHeight(int heightMeasureSpec){
        int result = 0;
        int specMode = MeasureSpec.getMode(heightMeasureSpec);
        int specSize = MeasureSpec.getSize(heightMeasureSpec);
        if(specMode == MeasureSpec.EXACTLY){
            result = specSize;
        } else {
            result = mHeight;
            if(specMode == MeasureSpec.AT_MOST){
                result = Math.min(result, specSize);
            }
        }
        this.mHeight = result;
        return result;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        for (int i=0;i<mArcEntityList.size() ;i++) {
            ArcEntity arcEntity = mArcEntityList.get(i);
            arcEntity.setCanvas(canvas);
            arcEntity.drawArc();
        }
    }

    /**
     * 开始动画
     */
    public void startAnimatorArc() {
        valueAnimator.start();
    }

    /**
     * 圆弧实体类
     */
    private class ArcEntity {
        private float startAngle;
        private float sweepAngle;
        private float endAngle;
        private Paint paint;
        private Canvas canvas;

        public ArcEntity(float startAngle, float endAngle,String color) {
            this.startAngle = startAngle;
            this.endAngle = endAngle;
            this.paint = new Paint();
            this.paint.setFlags(Paint.ANTI_ALIAS_FLAG);
            this.paint.setColor(Color.parseColor(color));
            this.paint.setStyle(Paint.Style.STROKE);
            this.paint.setStrokeWidth(mArcStrokeWidth);
            this.paint.setStrokeCap(Paint.Cap.ROUND);
        }

        public void drawArc() {
            canvas.drawArc(mRectF,startAngle,sweepAngle,false,paint);
        }

        public Canvas getCanvas() {
            return canvas;
        }

        public void setCanvas(Canvas canvas) {
            this.canvas = canvas;
        }


        public float getStartAngle() {
            return startAngle;
        }

        public void setStartAngle(float startAngle) {
            this.startAngle = startAngle;
        }

        public float getSweepAngle() {
            return sweepAngle;
        }

        public void setSweepAngle(float sweepAngle) {
            this.sweepAngle = sweepAngle;
        }

        public float getEndAngle() {
            return endAngle;
        }

        public void setEndAngle(float endAngle) {
            this.endAngle = endAngle;
        }

        public Paint getPaint() {
            return paint;
        }

        public void setPaint(Paint paint) {
            this.paint = paint;
        }
    }

    /**
     * 业务数据
     */
    public static class DataEntity{
        private String color;
        private float data;

        public DataEntity(String color, float data) {
            this.color = color;
            this.data = data;
        }
    }

}
